package com.cs.filter;

import com.cs.constant.GateWayConstant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class JWTCheckFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //登录的请求等放行
        if (GateWayConstant.ALLOW_URL.contains(path)) {
            return chain.filter(exchange);
        }
        List<String> heardTokens = request.getHeaders().get(GateWayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(heardTokens)) {
            //请求头中的token
            String heardToken = heardTokens.get(0);
            if (!StringUtils.isEmpty(heardToken)) {
                //截取获得jwt的token
                String jwtToken = heardToken.replace("bearer ", "");
                if (!StringUtils.isEmpty(jwtToken)) {
                    Boolean isToken = stringRedisTemplate.hasKey(GateWayConstant.TOKEN_JWT_PREFIX + jwtToken);
                    if (isToken) {
                        return chain.filter(exchange);//放行
                    }
                }

            }
        }
        //如果不是登录也没有token,返回数据给前端401
        ServerHttpResponse response = exchange.getResponse();
        //返回数据的类型
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("msg", "未授权");
        //格式转换
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //缓冲工厂
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
